<template>
  <div class="app-container">
    <!--    查询对话框-->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="580px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="14">
          <el-form-item label-width="125px" label="销售单号" prop="somDjbh">
            <el-input
              v-model="queryParams.somDjbh"
              placeholder="请输入销售单号"
              clearable
              style="width: 180px"
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="订单状态" prop="somZtbz">
            <el-select
              v-model="queryParams.somZtbz"
              style="width: 142px"
              placeholder="订单状态"
              clearable
              size="small"
            >
              <el-option
                v-for="dict in somZtbzOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="125px" prop="somPmgg">
            <span slot="label">
              <el-tooltip
                content="综合查询包含物料代码，品名规格，客户编码查询"
                placement="top"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
              综合查询
            </span>
            <el-input
              v-model="queryParams.somPmgg"
              clearable
              size="small"
              style="width: 400px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="125px" label="建立时间" prop="dateRange">
            <el-date-picker
              clearable
              size="small"
              v-model="dateRange"
              :clearable="false"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearch"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['marketing:som:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['marketing:som:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['marketing:som:remove']"
        >
          删除
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['marketing:som:import']"
          >
            批量下单
          </el-button>
        </el-col>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['marketing:som:export']"
        >
          导出
        </el-button>
      </el-col>
      <Tag type="dot" color="#3399ff">审核</Tag>
      <Tag type="dot" color="#FF44AA">结案待审批</Tag>
      <Tag type="dot" color="#bb0331">结案</Tag>
      <el-col :span="2.2" class="pageLocal">
        <Page
          style="margin-right: 0px"
          :current="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          @on-change="pageChange"
          simple
        ></Page>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      highlight-current-row
      v-loading="loading"
      :data="somList"
      border
      stripe
      :height="tableH"
      :cell-style="iCellStyle"
      ref="somTable"
      @row-click="clickRow"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="销售单号"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="somDjbh"
      />
      <el-table-column
        label="订单类型"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="somType"
      >
        <template #default="scope">
          <dict-tag :options="somAllTypeOptions" :value="scope.row.somType" />
        </template>
      </el-table-column>
      <el-table-column
        label="客户"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="somKhdm"
      >
        <template #default="scope">
          <dict-tag :options="allCustomerOptions" :value="scope.row.somKhdm" />
        </template>
      </el-table-column>
      <el-table-column
        label="客户编码"
        :show-overflow-tooltip="true"
        width="120"
        align="center"
        prop="somCustwldm"
      />
      <el-table-column
        label="本厂物料"
        :show-overflow-tooltip="true"
        width="130"
        align="center"
        prop="somWldm"
      />
      <el-table-column
        label="品名规格"
        :show-overflow-tooltip="true"
        width="280"
        align="center"
        prop="somPmgg"
      />
      <el-table-column
        label="订单数量"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="somDdsl"
      />
      <el-table-column
        label="下单日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="somXdrq"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.somXdrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="交货日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="somJhrq"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.somJhrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="计划导入"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="somPlanFlag"
      />
      <el-table-column
        label="备注"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="remark"
      />
      <el-table-column
        label="订单状态"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="somZtbz"
      >
        <template #default="scope">
          <dict-tag :options="somZtbzOptions" :value="scope.row.somZtbz" />
        </template>
      </el-table-column>
      <el-table-column
        label="建立人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="createBy"
      />
      <el-table-column
        label="建立日期"
        :show-overflow-tooltip="true"
        width="180"
        align="center"
        prop="createTime"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="审核人员"
        :show-overflow-tooltip="true"
        width="100"
        align="center"
        prop="somShry"
      />
      <el-table-column
        label="审核日期"
        :show-overflow-tooltip="true"
        align="center"
        prop="somShrq"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.somShrq, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['marketing:som:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['marketing:som:remove']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--  添加超发订单对话框  -->
    <el-dialog
      :title="title"
      v-model="addAdditionalView"
      :close-on-click-modal="false"
      draggable
      width="800px"
      append-to-body
    >
      <el-form
        ref="addAdditionalForm"
        :model="addAdditionalForm"
        :rules="addAdditionalRules"
        label-width="80px"
      >
        <el-col :span="12">
          <el-form-item label="单据类型" prop="somType">
            <el-select
              v-model="addAdditionalForm.somType"
              placeholder="请选择单据类型"
            >
              <el-option
                v-for="dict in addAdditionalScOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="父项营销单" prop="somType">
            <el-input
              v-model="addAdditionalForm.somDjbh"
              @blur="getFxSom(addAdditionalForm.somDjbh)"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="发货客户" prop="somKhdm">
            <el-select
              v-model="addAdditionalForm.somKhdm"
              disabled
              placeholder="请选择客户"
            >
              <el-option
                v-for="dict in customerOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="物料代码" prop="somDdsl">
            <el-input v-model="addAdditionalForm.somWldm" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="品名规格" prop="somDdsl">
            <el-input v-model="addAdditionalForm.somPmgg" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="原订单数量" prop="somDdsl">
            <el-input v-model="addAdditionalForm.somDdsl" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="交货日期" prop="somJhrq">
            <el-date-picker
              clearable
              size="small"
              v-model="addAdditionalForm.somNewJhrq"
              type="date"
              :clearable="false"
              value-format="yyyy-MM-dd"
              placeholder="选择交货日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="超发订单数量" prop="somNewDdsl">
            <el-input v-model="addAdditionalForm.somNewDdsl" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="订单备注" prop="remark">
            <el-input
              type="textarea"
              v-model="addAdditionalForm.remark"
              placeholder="请输入订单备注"
            />
          </el-form-item>
        </el-col>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddAdditionalView">取 消</el-button>
        <el-button type="primary" @click="submitAddAdditionalForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 添加或修改营销订单维护对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="12">
          <el-form-item label="订单编号" prop="somDjbh">
            <el-input v-model="form.somDjbh" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单据类型" prop="somType">
            <el-select
              v-model="form.somType"
              :disabled="title === '修改营销订单维护'"
              placeholder="请选择单据类型"
            >
              <el-option
                v-for="dict in somTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户编码" prop="somCustwldm">
            <el-input
              @blur="leaveInput(form.somCustwldm)"
              v-model="form.somCustwldm"
              :disabled="title === '修改营销订单维护'"
              placeholder="请输入客户编码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="somKhdm">
            <el-select
              v-model="form.somKhdm"
              :disabled="title === '修改营销订单维护'"
              placeholder="请选择客户"
            >
              <el-option
                v-for="dict in customerOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下单日期" prop="somXdrq">
            <el-date-picker
              clearable
              size="small"
              v-model="form.somXdrq"
              type="date"
              :clearable="false"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择下单日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交货日期" prop="somJhrq">
            <el-date-picker
              clearable
              size="small"
              v-model="form.somJhrq"
              type="date"
              :clearable="false"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择交货日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料代码" prop="somWldm">
            <el-input v-model="form.somWldm" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料品名" prop="somWldm">
            <el-input v-model="form.somPmgg" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单数量" prop="somDdsl">
            <el-input v-model="form.somDdsl" placeholder="请输入订单数量" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可用库存" prop="somKykc">
            <el-input v-model="form.somKykc" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="订单备注" prop="remark">
            <el-input
              type="textarea"
              v-model="form.remark"
              placeholder="请输入订单备注"
            />
          </el-form-item>
        </el-col>
      </el-form>
      <el-table
        v-if="title.indexOf('添加') > -1"
        height="220px"
        v-loading="loading"
        :data="selectedItmMstr"
      >
        <el-table-column
          label="客户编码"
          :show-overflow-tooltip="true"
          width="175"
          align="center"
          prop="itmCustwldm"
        />
        <el-table-column
          label="物料编码"
          :show-overflow-tooltip="true"
          width="175"
          align="center"
          prop="itmWldm"
        />
        <el-table-column
          label="品名规格"
          :show-overflow-tooltip="true"
          width="275"
          align="center"
          prop="itmPmgg"
        />
        <el-table-column
          label="操作"
          align="center"
          :show-overflow-tooltip="true"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleClick(scope.row)"
              v-hasPermi="['marketing:som:edit']"
            >
              应用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 营销单导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      :close-on-click-modal="false"
      width="450px"
      draggable
      append-to-body
    >
      <el-form
        ref="formUpload"
        :model="upload.data"
        :rules="upload.rules"
        label-width="80px"
      >
        <el-form-item label="订单类型" prop="somType">
          <el-radio-group v-model="upload.data.somType">
            <el-radio v-if="somUploadType !== 'KC'" label="SA" border
              >正常销售订单</el-radio
            >
            <el-radio v-if="somUploadType !== 'KC'" label="SK" border
              >库存销售订单</el-radio
            >
            <el-radio v-if="somUploadType === 'KC'" label="KC" border
              >备用库存订单</el-radio
            >
            <el-radio v-if="somUploadType === 'KC'" label="KY" border
              >跨月备库订单</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="somUploadType !== 'KC'"
          label="客户名称"
          prop="somKhdm"
        >
          <el-select
            v-model="upload.data.somKhdm"
            placeholder="可以在此指定客户"
          >
            <el-option
              v-for="dict in customerOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :data="upload.data"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        style="text-align: center"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="upload.open = false">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSom,
  getSom,
  delSom,
  addSom,
  updateSom,
  exportSom,
  importSomMstr,
  exportSomExample,
  getSomBySomDjbh,
  addScSom,
} from "@/api/marketing/som";

import { getAllCustomer, getAllCustomerTwo } from "@/api/project/customer";
import { getItmMstrByCustwldm } from "@/api/project/materiel";
import { getToken } from "@/utils/auth";
import { addMstr, updateMstr } from "@/api/system/mstr";

export default {
  name: "Som",
  data() {
    return {
      openSearch: false,
      // 遮罩层
      loading: true,
      tableH: 1,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      somDjbhs: [],
      currentData: [],
      // 日期范围
      dateRange: [
        this.$moment().startOf("month").toDate(),
        this.$moment().endOf("month").toDate(),
      ],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 营销订单维护表格数据
      somList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态标志字典
      somZtbzOptions: [],
      //根据客户代码查询出物料信息
      selectedItmMstr: [],
      // 订单类型字典
      somTypeOptions: [],
      //所有订单类型
      somAllTypeOptions: [],
      //客户类型
      customerOptions: [],
      //所有客户类型
      allCustomerOptions: [],
      //超发字典
      addAdditionalScOptions: [],
      //超发View
      addAdditionalView: false,
      addAdditionalForm: {
        somType: "SC",
        somFxDjbh: null,
        somNewJhrq: new Date(),
        somNewDdsl: 1,
      },
      //Som批量导入
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/marketing/som/importSom",
        data: {
          somType: this.$route.query.somType,
          somKhdm: "",
        },
        rules: {
          somKhdm: [
            {
              required: false,
              message: "如果需要指定客户出货，可以在此指定客户",
              trigger: "blur",
            },
          ],
          somType: [
            { required: true, message: "订单类型不能为空", trigger: "blur" },
          ],
        },
      },
      somUploadType: this.$route.query.somType,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: document.body.clientHeight > 900 ? 25 : 18,
        somDjbh: null,
        somZtbz: "1",
        somPmgg: null,
        somXdrqEnd: null,
        somXdrq: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        somCustwldm: [
          { required: true, message: "客户代码不能为空", trigger: "blur" },
        ],
        somWldm: [
          { required: true, message: "物料代码不能为空", trigger: "blur" },
        ],
        somDdsl: [
          { required: true, message: "订单数量不能为空", trigger: "blur" },
        ],
        somKhdm: [
          { required: true, message: "客户不能为空", trigger: "change" },
        ],
        somXdrq: [
          { required: true, message: "下单日期不能为空", trigger: "blur" },
        ],
        somJhrq: [
          { required: true, message: "交货日期不能为空", trigger: "blur" },
        ],
        somZtbz: [
          { required: true, message: "状态标志不能为空", trigger: "change" },
        ],
        somShrq: [
          { required: true, message: "审核日期不能为空", trigger: "blur" },
        ],
        somType: [
          { required: true, message: "订单类型不能为空", trigger: "change" },
        ],
      },
      addAdditionalRules: {
        somNewDdsl: [
          { required: true, message: "订单数量不能为空", trigger: "blur" },
        ],
        somNewJhrq: [
          { required: true, message: "交货日期不能为空", trigger: "blur" },
        ],
        somPmgg: [
          { required: true, message: "品名规格不能为空", trigger: "blur" },
        ],
      },
      //日期初始化
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_order_ztbz").then((response) => {
      for (let i of response.data) {
        if (i.dictValue === "2") {
          i.dictLabel = "审核";
        }
      }

      this.somZtbzOptions = response.data;
    });
    this.getDicts("sys_order_style").then((response) => {
      this.somTypeOptions = response.data;
    });

    this.getAllDicts("sys_order_style").then((response) => {
      this.somAllTypeOptions = response.data;
    });

    this.getDicts("sys_sc_order").then((response) => {
      this.addAdditionalScOptions = response.data;
    });
    getAllCustomer().then((response) => {
      for (let i of response.data) {
        i.dictLabel = i.cusName;
        i.dictValue = i.cusCode + "";
        i.listClass = "default";
      }

      this.customerOptions = response.data;
    });
    getAllCustomerTwo().then((response) => {
      for (let i of response.data) {
        i.dictLabel = i.cusName;
        i.dictValue = i.cusCode + "";
        i.listClass = "default";
      }

      this.allCustomerOptions = response.data;
    });
  },
  methods: {
    iCellStyle({ row, column, rowIndex, columnIndex }) {
      // 通过状态
      if (row.somZtbz == "2") {
        return "color:#3399ff";
      }
      // 结案申请状态
      else if (row.somZtbz == "3") {
        return "color:#FF44AA";
      }
      // 结案状态
      else if (row.somZtbz == "4") {
        return "color:#bb0331";
      }
    },
    /** 查询营销订单维护列表 */
    getList() {
      this.tableH = document.body.clientHeight - 280;
      if (this.dateRange !== null) {
        this.queryParams.somXdrq = this.moment(this.dateRange[0]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        this.queryParams.somXdrqEnd = this.moment(this.dateRange[1]).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.loading = true;
      listSom(this.queryParams).then((response) => {
        this.somList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //根据客户编号查询物料信息
    leaveInput(somCustwldm) {
      if (somCustwldm != null && somCustwldm.trim() !== "") {
        getItmMstrByCustwldm(somCustwldm).then((response) => {
          this.selectedItmMstr = response.data;
        });
      }
    },
    //返回数据
    requestUpload() {},
    beforeUpload(file) {
      //文件效验,判断文件格式和文件大小
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!extension && !extension2) {
        this.$message.error("上传模板只能是 xls、xlsx格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传模板大小不能超过 10MB!");
      }
      //上传图片
      let formData = new FormData();
      formData.append("file", file);
      importSomMstr(formData).then((response) => {});
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.openSearch = false;
    },
    // 表单重置
    reset() {
      this.form = {
        somId: null,
        somDjbh: null,
        somCustwldm: null,
        somWldm: null,
        somDdsl: null,
        somKhdm: null,
        somXdrq: this.moment().format(),
        somJhrq: this.moment().format(),
        somKykc: null,
        remark: null,
        somZtbz: null,
        createBy: null,
        createTime: null,
        somShry: null,
        somShrq: null,
        somJary: null,
        somJarq: null,
        somType: null,
        somChsl: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getFxSom(data) {
      if (data != null && data.trim() !== "") {
        getSomBySomDjbh(data).then((response) => {
          if (response.data) {
            this.addAdditionalForm = response.data;
            this.addAdditionalForm.somType = "SC";
            this.addAdditionalForm.somNewJhrq = new Date();
          }
        });
      }
    },
    // el-input__inner
    clickRow(row) {
      this.$refs.somTable.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.somId);
      this.somDjbhs = selection.map((item) => item.somDjbh);
      this.currentData = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleSearch() {
      this.reset();
      this.title =
        this.$route.query.somType === "KC" ? "查询备库订单" : "查询营销订单";
      this.openSearch = true;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.selectedItmMstr = [];
      this.open = true;
      this.title =
        this.$route.query.somType === "KC" ? "添加备库订单" : "添加营销订单";
    },
    //新增超发按钮
    addAdditional() {
      this.title = "添加超发订单";
      this.addAdditionalView = true;
    },
    cancelAddAdditionalView() {
      this.addAdditionalView = false;
    },
    submitAddAdditionalForm() {
      this.$refs["addAdditionalForm"].validate((valid) => {
        if (valid) {
          addScSom(this.addAdditionalForm).then((response) => {
            this.msgSuccess("新增成功");
            this.addAdditionalView = false;
            this.getList();
          });
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const somId = row.somId || this.ids;
      getSom(somId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title =
          this.$route.query.somType === "KC" ? "修改备库订单" : "修改营销订单";
      });
    },

    /** 应用按钮操作 */
    handleClick(row) {
      this.form.somWldm = row.itmWldm;
      this.form.somPmgg = row.itmPmgg;
      this.form.somCustwldm = row.itmCustwldm;
      this.form.somKykc = row.itmKc;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.somId != null) {
            updateSom(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSom(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      //已经审核的单据不能删除
      for (let i of this.currentData) {
        if (i.somZtbz === 2) {
          this.msgError("营销订单: [" + i.somDjbh + "] 已审核，无法删除~");
          return;
        } else if (i.somZtbz === 3) {
          this.msgError(
            "营销订单: [" + i.somDjbh + "] 正在结案申请中，无法删除~"
          );
          return;
        } else if (i.somZtbz === 4) {
          this.msgError("营销订单: [" + i.somDjbh + "] 已结案，无法删除~");
          return;
        }
      }
      const somIds = row.somId || this.ids;
      const somDjbh = row.somDjbh || this.somDjbhs;
      this.$confirm("确认删除销售单号[" + somDjbh + "]?删除不可恢复", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delSom(somIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    pageChange(page) {
      this.queryParams.pageNum = page;
      this.getList();
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有营销订单维护数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportSom(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    handleImport() {
      this.upload.title = "营销单导入";
      if (this.somUploadType === "KC") this.upload.title = "备库订单导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      exportSomExample().then((response) => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      // this.$refs['formUpload'].validate((valid) => {
      //   if (valid) {
      this.$refs.upload.submit();
      //   }
      // })
    },
  },
};
</script>

<style lang="scss" scoped></style>
